Promise原理示例代码
console.log('start method synchronously calling test');
setTimeout(() => {
console.log('setTimeout');
}, 0);
Promise.resolve().then(() => {
console.log('promise');
});
console.log('end method synchronously calling test');
console.log("before asyncFunc");
async function asyncFunc(_pos)
{
let myPromise = new Promise(function(myResolve) {
console.log("before setTimeout promise in asyncFunc with _pos:"+_pos);
setTimeout(function() {
myResolve("4000毫秒时间已到 with _pos:"+_pos);
console.log("4000毫秒已到");
},4000);
console.log("after setTimeout promise in asyncFunc with _pos:"+_pos);
});
return myPromise;
}
console.log("after asyncFunc");
console.log("before testAsyncFunc");
async function testAsyncFunc()
{
setTimeout(() => {
console.log('setTimeout2');
}, 0);
Promise.resolve().then(() => {
console.log('promise2');
});
console.log("before asyncFunc")
let afPromise=asyncFunc("first");
//asyncFunc("first");
console.log("after asyncFunc");
console.log("before asyncFunc.then");
asyncFunc("second").then(function(value) {
console.log(`ayncFunc.then's return value:${value}`);
})
console.log("after asyncFunc.then");
console.log("before await asyncFunc");
let funcVal=await asyncFunc("third");
console.log("await-asyncFunc's return value:"+funcVal);
console.log("after await asyncFunc");
console.log("before afPromise.then");
afPromise.then(function(value) {
console.log(`afPromise.then's return value:${value}`);
})
console.log("after afPromise.then");
console.log("exit testAsyncFunc");
}
console.log("after testAsyncFunc");
console.log("beofore testAsyncFunc.then");
testAsyncFunc().then(console.log('testAsyncFunc.then执行结束'));
console.log("after testAsyncFunc.then");
console.log("-----------分隔符-----------");
代码输出结果如下:


浙公网安备 33010602011771号