1.Promise
(1)Promise 新建后就会立即执行。
let promise = new Promise(function(resolve, reject) {
console.log('Promise');
resolve();
});
promise.then(function() {
console.log('resolved.');
});
console.log('Hi');
打印结果为:
// Promise
// Hi!
// resolved
(2).利用方法返回 promise
.then(fn1(), fn2());
fn1()是执行的resolve函数,fn2()执行的是fn2函数
function timeout(flag) {
return new Promise((resolve, reject) => {
if(flag){
resolve("true");
}else{
reject("false")
}
});
}
timeout(false).then((value) => {
console.log(value);
},(value) => {
console.log(value)
});
2.async函数返回一个 Promise 对象,可以使用then方法添加回调函数。
当函数执行的时候,一旦遇到await就会先返回,等到异步操作完成,再
接着执行函数体内后面的语句。
async function getStockPriceByName(name) {
const symbol = await getStockSymbol(name);
const stockPrice = await getStockPrice(symbol);
return stockPrice;
}
getStockPriceByName('goog').then(function (result) {
console.log(result);
});
下面代码指定 50 毫秒以后,输出hello world。
function timeout(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function asyncPrint(value, ms) {
await timeout(ms);
console.log(value);
}
asyncPrint('hello world', 50);
async 函数的使用方式
// 函数声明
async function foo() {}
// 函数表达式
const foo = async function () {};