【问题标题】:Using the promise constructor to send back a value to the server使用 promise 构造函数将值发送回服务器
【发布时间】:2017-10-19 12:39:10
【问题描述】:

我正在使用promisify 函数来promisify XHR,我想知道如何获取响应,如果响应成功则将其发布回服务器。

我正在做这样的事情

function createChannel(method, url) {
    return new Promise(function (resolve, reject) {
        xhr.open(method, url, true);
        xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onload = function () {
        if (xhr.readyState == 4 ) {
            var hashValue = resolve(JSON.parse(xhr.responseText));
            console.log(hashValue);
        }
        else {
            reject({
                status: this.status,
                statusText: xhr.statusText
            });
        }
    };
    xhr.onerror = function () {
            reject({
                status: this.status,
                statusText: xhr.statusText
            });
        };
    xhr.send(json);
});
}
createChannel(method, url)
    .then(function (datums) {
    console.log(datums)
}).catch(function (err) {
    console.error('Sorry There Was An Error!', err.statusText);
});

如果这个 createChannel 成功,我想获取 hashvalue 变量,并向服务器发出请求以获取新值。

.then(function (createChannel) {
    console.log(createChannel);    
});

这可以使用promise吗? 谢谢你的建议。

【问题讨论】:

  • 不清楚“再次发送”是什么意思?当您获得已解决的承诺并在 .then() 处理程序中获得您的 datums 值时,此时您想做什么?
  • 嘿@jfriend00 对我选择的措辞感到抱歉,当我得到解决的承诺时,我想向服务器/url 发出新请求。我想获取哈希变量并发出新的发布请求
  • 好的,我在我的回答中表明了这一点。

标签: javascript node.js callback promise xmlhttprequest


【解决方案1】:

在您的 .then() 处理程序中,您只需发出一个新请求并返回该承诺,并将其链接到第一个:

createChannel(method, url).then(function (datums) {
    console.log(datums);
    // call some other async function here that returns a promise
    return someOtherFunctionThatReturnsAPromise(datums);
}).then(function(finalResult) {
    console.log(finalResult);        
}).catch(function (err) {
    console.error('Sorry There Was An Error!', err.statusText);
})

【讨论】:

  • 谢谢你,这似乎是我弄糊涂了,我会试试看它是否有效。
  • 你好@jfriend00,我想知道,createchannel 是否已经保存了 hashvalue 变量的值?我不知道我是否在问一个我应该已经知道的愚蠢问题。感谢您的帮助
  • 我想通了,谢谢。
  • @PythonRookie - 在您的代码中,参数datums 将是JSON.parse(xhr.responseText) 的结果。 xhr 函数中的 hashValue 变量没有意义,因为 resolve() 没有返回值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-23
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
相关资源
最近更新 更多