标准的方式来做到asyntask为了与承诺 [英] Standard way to do asyntask in order with promise

查看:151
本文介绍了标准的方式来做到asyntask为了与承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有

我是pretty新的承诺,我想要做的是:

I am pretty new to promise, what I want to do are:

[1]下载文件中的,当A下载,然后下载文件B,B之后已经准备好,然后下载载荷C。

[1] Download file A, when A downloaded, then download file B, after B is ready, then download load C.

[2]制作一个函数来下载文件A,不管它被调用多少次,只降档一次。

[2] Make a function to download file A, no matter how many times it been called, it only down file once.

[1]和[2]是不相关的任务。你能帮助我与其中任何一个或两个。

[1] and [2] are not related tasks. You can help me with either one of them or Both.

谁能给我一份有承诺一个简单的例子?谢谢你。

Could anyone give me a simple example with promise? Thanks.

推荐答案

在使用Node.js的青鸟承诺库,这里有三种方法:

Using the Bluebird promise library in node.js, here are three approaches:

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

完全连续,每一步codeD单独

Purely Sequential, each step coded separately

// 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 in parallel, collect results when they are all done

// 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
});

这篇关于标准的方式来做到asyntask为了与承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆