S. *_*har 10 javascript promise
基本承诺问题:
console.log('Promise START');
function makeFullJSON(time) {
return new Promise((resolve, reject) => {
setTimeout(resolve, time, [time]);
})
}
var p1 = makeFullJSON(1000);
var p2 = makeFullJSON(500);
var p3 = makeFullJSON(750);
p1.then(array => {
console.log('Promise 1 complete', array);
});
p2.then(array => {
console.log('Promise 2 complete', array);
});
p3.then(array => {
console.log('Promise 3 complete', array);
});
Promise.all([p1, p2, p3]).then(arrayOfAllResolvedValues => {
console.log('Array of resolved values:', arrayOfAllResolvedValues);
});
console.log('Promise END');Run Code Online (Sandbox Code Playgroud)
代码输出是:
Promise START
Promise END
Promise 2 complete [ 500 ]
Promise 3 complete [ 750 ]
Promise 1 complete [ 1000 ]
Array of resolved values: [ [ 1000 ], [ 500 ], [ 750 ] ]
Run Code Online (Sandbox Code Playgroud)
你如何重写代码,输出是:
Promise START
Promise 2 complete [ 500 ]
Promise 3 complete [ 750 ]
Promise 1 complete [ 1000 ]
Array of resolved values: [ [ 1000 ], [ 500 ], [ 750 ] ]
Promise END
Run Code Online (Sandbox Code Playgroud)
完成后想要发生的任何事情都将传递给您传递给它的箭头函数。
console.log('Promise START');
function makeFullJSON(time) {
return new Promise((resolve, reject) => {
setTimeout(resolve, time, [time]);
})}
var p1 = makeFullJSON(1000);
var p2 = makeFullJSON(500);
var p3 = makeFullJSON(750);
p1.then(array => {
console.log('Promise 1 complete', array);});
p2.then(array => {
console.log('Promise 2 complete', array););
p3.then(array => {
console.log('Promise 3 complete', array);});
Promise.all([p1, p2, p3]).then(arrayOfAllResolvedValues => {
console.log('Array of resolved values:', arrayOfAllResolvedValues);
console.log('Promise END');
});
Run Code Online (Sandbox Code Playgroud)
为了放弃立即执行程序,并开始编写仅在所有三个诺言都解决后才会发生的代码,因为这听起来像您想发生,那么我建议您直接在代码下方创建一个新函数,以包含将要执行的代码喜欢在解决后发生,并通过传递该函数,例如:Promise.all([p1, p2, p3]).then(newFunctionName)。以这种方式将其可视化可能会更容易,至少直到您习惯于思考它的精确工作方式为止。
首先修复语法错误。然后将console.log移动到整个过程结束的地方:
console.log('Promise START');
function makeFullJSON(time) {
return new Promise((resolve, reject) => {
setTimeout(resolve, time, [time]);
})}
var p1 = makeFullJSON(1000);
var p2 = makeFullJSON(500);
var p3 = makeFullJSON(750);
p1.then(array => {
console.log('Promise 1 complete', array);});
p2.then(array => {
console.log('Promise 2 complete', array);}); // fixed syntax error here
p3.then(array => {
console.log('Promise 3 complete', array);});
Promise.all([p1, p2, p3]).then(arrayOfAllResolvedValues => {
console.log('Array of resolved values:', arrayOfAllResolvedValues);
console.log('Promise END');
});Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23053 次 |
| 最近记录: |