如何让异步readFile方法遵循node.js中的顺序 [英] How to let asynchronous readFile method follow order in node.js

查看:91
本文介绍了如何让异步readFile方法遵循node.js中的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码

var fs = require('fs');
console.log("1");
fs.readFile("./index.js", function(err, data) {
    if (err) {
         console.log("err");
    }
    console.log("2");
});
console.log("3");

结果将是

1
3
2

但是我想要1 2 3我已经浏览了文件系统的文档,并说With the asynchronous methods there is no guaranteed ordering.,所以该文档说如果我想要我的代码结果1 2 3应该是

But I want 1 2 3 I have look through filesystem's document and it says With the asynchronous methods there is no guaranteed ordering. so the document says if I want my code result 1 2 3 it should be

var fs = require('fs');
console.log("1");
fs.readFile("./index.js", function(err, data) {
    if (err) {
         console.log("err");
    }
    console.log("2");
    console.log("3");
});

但是如果我要构建一个具有很多其他功能的系统,这是短代码,那么在此代码之后我们不能嵌套所有内容,因为该功能在被其他功能使用后需要工作那么有没有办法让fs.readFile正常工作,但又不让所有代码在fs代码之后都需要工作?

But it's for short code if I'm building a system which has a lot of other function needs to be after this code we can't nested all in because the function need to be work after it will be use by other functions so is there a way to let the fs.readFile work in order but not incuding all the code need to work after it in fs code?

function servedatastart() {

    if (urlcontentbasic(urlslug) != "err") {
        responsearray["data"] = urlcontentbasic(urlslug);
    } else {
        // callback function
        console.log("urlex");
        urlex("none", urlslug); // this function I use fs.readFile(urlslug, function...
    }
    console.log("other function");
    //other function
    cuswriteheader();
    includescript();
    writefooter()
    res.end();   
}

推荐答案

使用async.waterfall,它允许您按顺序运行异步函数,每个函数都取决于上一个函数来完成.当最后一个函数完成调用主回调时,每个函数都可以将结果传递给下一个. 检查 https://caolan.github.io/async/docs.html

Use async.waterfall, it allows you to run asynchronous functions in order, each function depends on the previous one to complete. when the last function completes the main callback is called, each function can pass the result to the next one. check https://caolan.github.io/async/docs.html

var fs = require('fs');
var async = require('async');

async.waterfall([
    function (callback) {
        console.log("1");
        callback();
    },
    function (arg1, callback) {
        fs.readFile("./index.js", callback);
        console.log("2");
    },
    function (arg2, callback) {
        console.log("3");
        callback()
    }
], function(err, res){

});

这篇关于如何让异步readFile方法遵循node.js中的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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