如何将变量传递给Promise链中另一个文件中的异步函数

时间:2019-08-20 21:26:19

标签: javascript node.js ecmascript-6 promise es6-promise

如何在promise中将变量传递给另一个文件中的异步函数?

body {
  background-image: url('https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/microsoft/209/bread_1f35e.png');
  background-repeat: no-repeat;
  font-size: 110px;
  padding: 0.25em;
}

img {
  position: absolute;
  left: 10px;
  top: 10px;
  z-index: -1;
}

img + img {
  top: 25px;
  left: 25px;
}
?
<img src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/microsoft/209/herb_1f33f.png" alt="greens in the sandwich">
<img src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/microsoft/209/bacon_1f953.png" alt="meat between the bread">

2 个答案:

答案 0 :(得分:2)

像其他任何变量一样传递变量-异步活动不会阻止您这样做:

thisFunc
    .asyncFunction(foo)
    .then(...)

然后在asyncFunction中添加参数:

const asyncFunction = async foo => {...};

答案 1 :(得分:0)

异步功能不会阻止您将数据传递给异步功能。

// file2.js

const asyncFunction = async (foo) => {
    console.log(foo); // <-- and do stuff with foo here
}

// file1.js
// const thisFunc = require('./file2');
const foo = "bar";
const newPromise = new Promise((resolve, reject) => {
    // thisFunc.
    asyncFunction(foo) // <-- I want to pass foo here
        .then((data)=>{
            console.log(data);
            resolve('From newPromise ');
        })
});

newPromise.then(console.log);