【问题标题】:Standard way to do asyntask in order with promise按照承诺按顺序执行异步任务的标准方法
【发布时间】:2015-03-12 09:58:26
【问题描述】:

全部:

我很新承诺,我想做的是:

[1]下载文件A,当A下载完毕后,再下载文件B,待B准备好后,再下载加载C。

[2]制作一个下载文件A的函数,无论调用多少次,只下载一次。

[1] 和 [2] 不是相关的任务。您可以帮助我解决其中之一或两者。

谁能给我一个简单的承诺示例?谢谢。

【问题讨论】:

  • 你在用 node.js 写东西吗?还是在浏览器中?或者在其他环境中。我们无法在不知道哪个环境的情况下提供代码。你试过任何代码吗?你使用的是哪个 promise 库?
  • @jfriend00 我打算在node.js中做

标签: asynchronous promise


【解决方案1】:

在 node.js 中使用 Bluebird Promise 库,这里有三种方法:

// load and promisify modules
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require('fs'));

纯顺序,每一步单独编码

// purely sequential
fs.readFileAsync("file1").then(function(file1) {
    // file1 contents here
    return fs.readFileAsync("file2");
}).then(function(file2) {
    // file2 contents here
    return fs.readFileAsync("file3");    
}).then(function(file3) {
    // file3 contents here
}).catch(function(err) {
    // error here
});

并行读取,完成后收集结果

// read all at once, collect results at end
Promise.map(["file1", "file2", "file3"], function(filename) {
    return fs.readFileAsync(filename);
}).then(function(files) {
    // access the files array here with all the file contents in it
    // files[0], files[1], files[2]
}).catch(function(err) {
    // error here
});

从数组中顺序读取

// sequential from an array
Promise.map(["file1", "file2", "file3"], function(filename) {
    return fs.readFileAsync(filename);
}, {concurrency: 1}).then(function(files) {
    // access the files array here with all the file contents in it
    // files[0], files[1], files[2]
}).catch(function(err) {
    // error here
});

【讨论】:

  • 感谢您的回复。这有帮助。您能否举一些 AngularJS 中内置的 promise 或节点 promise 模块的示例:npmjs.com/package/promise
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多