【问题标题】:Promise result and its processing into two separate filesPromise 结果及其处理成两个单独的文件
【发布时间】:2018-06-26 15:54:32
【问题描述】:

在我的脚本中,我需要创建一个 XMLrequest,从服务器获取响应(如果已解决),对其进行解析并将解析结果放入变量中。

只有以后,有了这个变量,我才能做很多事情。

所以基本上,我试图将此类解析器对象的创建与我的其余代码分开,以便:

  • 将上述过程放入外部脚本中的函数中,我可以在需要时调用该函数。
  • 我的所有代码都没有包含在 .then() 方法中
  • 将我的代码组织成逻辑文件,每个文件专门用于特定任务

所以我想出了这段代码(只是一个示例)来解释我的需求。 由于我对异步编程相当陌生,考虑到在我的情况下响应应该非常快地解决(或拒绝),这样做是否可以?

如果没问题,我会将它放在一个单独的文件中,以便能够导入它并从我需要的任何地方调用testing()(或任何名称)。

function delay(input) {
    return new Promise(function(resolve, reject) {
        // some async operation here
        setTimeout(function() {
            // resolve the promise with some value
            resolve(input + 10);
        }, 500);
    });
}

function testing() {delay(5).then(result => {return document.write(result)})};

testing();

编辑

好的,所以我想我遇到了问题,这要归功于@DrewReese 的回答和 cmets 中的链接。

我正在尝试解决这种的情况:上面的代码误导了我的观点,但我想没有真正简单的解决方案。 看这段代码(和上面的基本一样,除了最后三行):

function delay(input) {
    return new Promise(function(resolve, reject) {
        // some async operation here
        setTimeout(function() {
            // resolve the promise with some value
            resolve(input + 10);
        }, 500);
    });
}

function testing() {delay(5).then(result => {return result})};

var test = testing();
document.write(test);

所以在这种情况下,我知道当我定义test 时,输出是'undefined',因为testing() 中的Promise 尚未解决。

我要解决的问题是:是否有(如果有的话)只有在 Promise 解决时才定义测试而不将其包装在 then() 中并且可能在未解决时输出不同的东西(例如“正在加载...")。

我基本上不知道是否可以检查一个变量是否有一个 Promise 待处理并输出两个不同的值:它何时等待以及何时解决/拒绝。

希望我已经足够清楚了,否则我会进行更多测试并在需要时提出另一个问题。

【问题讨论】:

  • 你有什么问题?代码运行良好。
  • "这样可以吗"。问题的意思是:“我是否真的错过了一些需要注意的事情,或者这样做完全没问题。例如:有没有更好(或完全不同)的方法来做到这一点?”我找不到任何将检索 Promise 响应的逻辑分离并将其结果放入两个单独文件的示例。
  • 还有其他方法可以做到这一点,比如 ES6 异步函数和await
  • 魔鬼在细节中。您的小sn-p 很好,很难知道您的实际应用程序是否可以正常工作而没有看到它。如果在异步函数中设置变量,则需要确保在实际设置之前不要尝试使用它。见stackoverflow.com/questions/14220321/…stackoverflow.com/questions/23667086/…
  • 如果我理解正确,您似乎有两个问题:(1)如何不从 Promise 中获取未定义的返回值,以及(2)有没有办法测试 a 的挂起状态运行承诺。第一个的答案是按照@Barmar 的建议和我的例子......使用异步/等待。对于第二个问题,我只是用谷歌搜索了它,似乎有一些方法/示例可以检查 Promise 的待处理状态,但它们似乎都是 Promise 的反模式......只需等待它解决并“回调”,或者拒绝...尝试监控 Promise 的状态并没有强有力的论据。

标签: javascript ajax asynchronous promise


【解决方案1】:

promise(promise 链)的全部意义在于通过扁平化你的“链”来逃离“嵌套地狱”,所以是的,当你的 promise 链解析代码块时,它返回一个 promise,它是 then -有能力的。我希望这有助于说明:

someAsyncHttpRequest(parameter) // <- Returns Promise
    .then(result => {
        // do something with result data, i.e. extract response data, 
        //  mutate it, save it, do something else based on value
        ...
        // You can even return a Promise
        return Promise.resolve(mutatedData);
    })
    .then(newData => {  // <- mutadedData passed as parameter
        // do new stuff with new data, etc... even reject
        let rejectData = processNewData(newData);
        return Promise.reject(rejectData);
    })
    .catch(err => {
        console.log('Any caught promise rejection no matter where it came from:', err);
    })
    .finally(() => {// You can even run this code no matter what});

如果您需要使用您在链中设置的任何变量值,那么您需要使外部函数异步并等待承诺链的解析:

asyncFunction = async (parameter) => {
    let asyncValue;

    await someAsyncHttpRequest(parameter)
        .then(result => {
            ...
            asyncValue = someValue;
            ...
        });
    // safe to use asyncValue now
};

所以对你来说:

function delay(input) {
    return new Promise(function(resolve, reject) {
        // some async operation here
        setTimeout(function() {
            // resolve the promise with some value
            resolve(input + 10);
        }, 500);
    });
}

**async** function testing() { // Declare this an asynchronous function
    let value = **await** delay(5); // Now you can await the resolution of the Promise
    console.log(value); // Outputs resolved value 15!
    return value; // Just returns resolved Promise
}

var test = testing();

console.log(test); 
/** Outputs the Promise!
   Promise {<pending>}
     __proto__:Promise
     [[PromiseStatus]]:"resolved"
     [[PromiseValue]]:15
*/

test.then(console.log)); // Outputs returned resolved value, 15

【讨论】:

  • 就像你上一个例子一样,将 await 与 then 混合起来很奇怪。为什么不直接将someAsyncHttpRequest 的结果分配给asyncValue
  • 这就是这段代码的作用。 someAsyncHttpRequest 返回一个包含您要保存的结果的承诺。 Promise 使用回调,因此没有 await,javascript 将愉快地处理请求并伴随...等待它暂停函数的执行并首先等待 promise 链的解决,然后再继续。
  • 我想我不是很清楚,抱歉。我的观点是这更符合 aync/await 的习惯:let asyncValue = await someAsyncHttpRequest(parameter)。不需要then()
  • 哦,我明白你的意思了。我只是试图演示从链中设置变量,所以使用传递的结果有点过于简单了。
猜你喜欢
  • 2017-12-28
  • 1970-01-01
  • 1970-01-01
  • 2017-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
相关资源
最近更新 更多