首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在node js中将异步转换为同步

如何在node js中将异步转换为同步
EN

Stack Overflow用户
提问于 2020-04-05 00:08:33
回答 2查看 587关注 0票数 0

我是nodejs.And的新手,现在我在node js中遇到了异步和同步的问题。

下面是我的代码:

代码语言:javascript
复制
var time_begin = Date.now();
console.log("begin time:" + time_begin);

arr_a = ['a', 'b', 'a', 'b', 'a', 'b']

async function iterTrans (arr_a) {

    var txs_arr_tmp = [];
    for(let aInfo of arr_a) {
        var fs = require('fs');
        if (aInfo == "a") {
            fs.readFile("./debug.json", function (error_file, data_file) {
                if (error_file) {
                    console.log(error_file)
                } else {
                    txs_arr_tmp.push("a");
                }
            });

        } else {
            txs_arr_tmp.push("b");
        }
    }
    return txs_arr_tmp;
}

iterTrans(arr_a).then((txs_arr_tmp) => {

    var content_str = JSON.stringify(txs_arr_tmp);
    console.log(content_str);
})

我希望控制台将打印:

代码语言:javascript
复制
["a","b","a","b","a","b"]

但实际上我得到了:

代码语言:javascript
复制
["b","b","b"]

我已经学习并尝试了一些关于异步到同步的方法,但我没有在readFile中使用异步方法。

那么怎样才能得到"a","b","a","b","a","b“呢?谁能给我一些建议?

非常感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-04-05 01:15:40

下面是我编写函数的方法。由于您的Node.js版本不支持fs.promises API,因此您可以使用util.promisify()fs.readFile()从回调API转换为promise API,然后使用Array.prototype.map()创建promises数组并与Promise.all()并行地await readFile()调用

代码语言:javascript
复制
const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);

const time_begin = Date.now();
console.log("begin time:" + time_begin);

const arr_a = ['a', 'b', 'a', 'b', 'a', 'b'];

async function iterTrans (arr_a) {
  // array map allows parallel asynchronicity
  const txs_arr_tmp_promises = arr_a.map(async aInfo => {
    // use early return (to avoid nesting large blocks inside if statements)
    if (aInfo !== 'a') return 'b';

    // let await throw here if file error occurs
    const data_file = await readFile('./debug.json');
    return 'a';
  });

  return Promise.all(txs_arr_tmp_promises);
}

iterTrans(arr_a).then(txs_arr_tmp => {
  const content_str = JSON.stringify(txs_arr_tmp);
  console.log(content_str);
}).catch(error => {
  // handle errors here
  console.log(error);
});
票数 1
EN

Stack Overflow用户

发布于 2020-04-05 00:57:35

您不能将某些东西异步转换为同步,但您可以让rest实现等待异步函数完成

代码语言:javascript
复制
var time_begin = Date.now();
console.log("begin time:" + time_begin);
arr_a = ['a', 'b', 'a', 'b', 'a', 'b']

async function iterTrans(arr_a) {
  var txs_arr_tmp = [];
  for (let aInfo of arr_a) {
    const fs = require('fs').promises;
    if (aInfo == "a") {
      try {
        await fs.readFile("./debug.json")
        txs_arr_tmp.push("a");
      } catch (error) {
        console.log(error)
        var obj_addr = {
          "success": false,
          "error_no": 1,
          "error_info": "err with addrs"
        }
        return res_send.jsonp(obj_addr);
      }
    } else {
      txs_arr_tmp.push("b");
    }
  }
  return txs_arr_tmp;
}

iterTrans(arr_a).then((txs_arr_tmp) => {
  var content_str = JSON.stringify(txs_arr_tmp);
  console.log(content_str);
}) 

如果fs的简化方法不可用

代码语言:javascript
复制
var time_begin = Date.now();
console.log("begin time:" + time_begin);
arr_a = ['a', 'b', 'a', 'b', 'a', 'b']

async function iterTrans(arr_a) {
  var txs_arr_tmp = [];
  for (let aInfo of arr_a) {
    let util = require('util');
    const readFile = util.promisify(require('fs').readFile);
    if (aInfo == "a") {
      try {
        await readFile("./debug.json")
        txs_arr_tmp.push("a");
      } catch (error) {
        console.log(error)
        var obj_addr = {
          "success": false,
          "error_no": 1,
          "error_info": "err with addrs"
        }
        // return res_send.jsonp(obj_addr);
      }
    } else {
      txs_arr_tmp.push("b");
    }
  }
  return txs_arr_tmp;
}

iterTrans(arr_a).then((txs_arr_tmp) => {
  var content_str = JSON.stringify(txs_arr_tmp);
  console.log(content_str);
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61030915

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档