需要第三个异步函数执行后的前两个在js执行
Need third async function to execute after the execution of first two in js?
条件
first two async functions start at the same time
don't know which one finish first
需要在这两个函数完成后执行第三个函数。
尝试使用承诺。如果可能的话,请使用承诺和其他方式帮助实现它。
something I tried not sure if it is right.
function foop(a){
return new Promise(function(resolve, reject){
window.setTimeout(function(){
console.log("first promise executed");
}, 2000);
window.setTimeout(function(){
console.log("second promise executed");
if(a>5) resolve(a+10);
}, 2000);
if(a<5) reject("error");
});
}
foop(12).then(function(val){
window.setTimeout(function(){
console.log("first then executed -"+ val);
}, 1000);
}).then(function(val){
window.setTimeout(function(){
console.log("second then executed -"+ val);
}, 500);
}).catch(function(err){
console.log("error occured");
});
期望输出顺序
first promise executed //or second promise executed
second promise executed // or first promise executed
first then executed -22 //only executed after first two async completes in any order
second then executed -22 // execute after the third async completes (first then completes)
error occured // in case of reject
使用Promise.all
:
console.log('starting...');
// example function: sleep for 'delay' ms then resolve to 'value'
const wait = (delay, value) => new Promise((resolve, reject) => setTimeout(() => { console.log('done:', value); resolve(value); }, delay));
// start two async functions at the same time
// (in this case, they complete in random order)
const firstPromise = wait(900 + 200 * Math.random(), 'first');
const secondPromise = wait(900 + 200 * Math.random(), 'second');
// Promise.all will wait until all promises given are resolved:
Promise.all([ firstPromise, secondPromise ])
.then((results) => {
// if all promises are resolved, results is an array of the
// result values from each, in the order they are given
console.log(results); // = [ 'first', 'second' ]
// run some other function again...
return wait(500, 'third');
})
.then((result) => {
// 'result' is the result from the third function
// more functions, etc...
return wait(800, 'fourth');
})
.then((result) => {
// you can even use Promise.all again to run two functions simultatenously, inside a .then
return Promise.all([
wait(1100, 'fifth'),
wait(900, 'sixth')
]);
})
// etc...
.catch((error) => {
// if any promise fail, error will be the error from the first to fail
console.error('Error:', error);
});
相关文章:
- Meteor:插入集合后如何执行JS
- 如何在Odoo 9中执行JS文件中的函数
- 匿名自执行js函数内部的全局变量在外部仍然可用
- NumericTextBox-当用户键入数字时执行JS计算.能做到吗
- 引导:响应式设计-当窗口大小从980px调整到979px时执行JS
- 对页面上的所有ID执行JS功能
- 从浏览器访问页面时执行js函数's后退按钮
- 源代码未完全执行.(JS)
- 在执行JS脚本后监视对DOM的更改
- 在表单同步提交后执行 js 吗?
- 在 ubuntu 14.04 VPS 上执行.js文件错误
- 从PHP插入时在MongoDB上执行JS
- 在将ajax内容应用到元素后执行js函数
- Windows Phone浏览器控件执行JS函数来替换src属性
- 到达新页面后执行js
- 用C#在Win 8.1 Chakra中执行JS的一个失败的最小例子
- 在sharepoint显示模板中执行JS
- 在Bootstrap popover内部执行JS
- 从引导程序popover内容内部执行js
- 顺序执行js