简体   繁体   English

如何将Node Promise和http一起使用?

[英]How do I use node Promise and http together?

I am trying to learn about Promises in node. 我正在尝试了解节点中的Promises。 I want to be able to use the http.request as a promise. 我希望能够将http.request用作承诺。 This is what I have learnt so far. 这是我到目前为止所学到的。

I set up a test case using setTimeout as shown below: 我使用setTimeout设置了一个测试用例,如下所示:

var makePromise = (txt, milli) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {  // fn(cb)
            console.log("I promise to...")
            resolve(txt)
        }, milli)
    });
}

var p = makePromise("Come Home", 3000);
var q = makePromise("Go Shopping", 1000);

var tasks = [p, q];

console.log("Start with ", tasks);

Promise.all(tasks).then((res) => {
    console.log(res);
    console.log("Finish");
})

This works fine. 这很好。 Now I thought that all I would need to do was replace the setTimeout function with the appropriate http.request. 现在我想我所要做的就是用适当的http.request替换setTimeout函数。 But it doesn't seem to be as straightforward as that. 但这似乎并不那么简单。

Here is the current attempt at this. 这是当前的尝试。

var makePromise = (collection, item) => {
    var options = {
        method: "PUT",
        port: 9000,
        host: "localhost",
        path: `/${collection}/item/${item.Label.itemUUID}`,
        headers: {
            "Accept": "application/json",
            "Content-type": "application/json",
            "Content-length": JSON.stringify(req.body).length
        }
    };
    console.log(JSON.stringify(options));

    var httpPromise = new Promise((resolve, reject) => {
        var vot = http.request(options, (votResponse) => {
            var responseBody = [];
            votResponse.on('data', (chunk) => {
                console.log(`Got ${chunk.length} ${chunk}`);
                responseBody.push(chunk);
            });
            votResponse.on('end', () => {
                console.log("End of http");
                console.log("After web proxy like call - raw data: ", Buffer.concat(responseBody).toString());
                responseBody.json = JSON.parse(Buffer.concat(responseBody).toString());
                resolve(responseBody.json);
            });
            votResponse.on('error', (err) => {
                reject(err);
            });
        })
        vot.write(JSON.stringify(item));
        vot.end();
    });
    return httpPromise;
};

I know there are libraries like "request-promise" that can help, but I am keen to get a deeper understanding of the native operations before using a library. 我知道有一些像“请求承诺”之类的库可以提供帮助,但是我希望在使用库之前对本机操作有更深入的了解。 Can anyone point out how I might get this approach to work? 谁能指出我如何使这种方法起作用?

The calling code is shown here: 调用代码如下所示:

var collection = req.params.collection;
var patchInstruction = req.body.patchInstruction;
switch (patchInstruction) {
    case "CASCADE DELETE": 
        console.log("CASCADE DELETE on", collection, req.body.item);
        var tasks = [req.body.item].concat(req.body.asSubject).concat(req.body.asObject);
        tasks = tasks.map((e, i, a) => {
            e.Item = "DELETED"
            return makeDeletePromise(collection, e); // a promise to do the http PUT
        });
        console.log("WIP ", tasks);
        Promise.all(tasks).then((res) => {
            console.log("To client --> ",res);
            res.send(res);  
        })
        break;
    default:    
        console.log("No path to ",patchInstruction);
        res.send(409);
        break;
}

The call to port 9000 never happens. 永远不会发生对端口9000的调用。

It's always a good idea to end a promise chain with a catch call. 它总是一个好主意,以结束与一个承诺链条catch通话。 Otherwise, any error that happens inside a promise chain would be "swallowed" -- you simply will not see it. 否则,在诺言链中发生的任何错误都会被“吞噬”-您根本看不到它。

So, any time there is a then there should be a catch . 因此,任何时候有then应该有一个catch

Promise.all(tasks).then((res) => {
    console.log("To client --> ", res);
    res.send(res);
}).catch((err) => console.log(err));

I believe, an error is somewhere near res.send(res) , because http's res is shadowed by local res . 我相信,错误是在res.send(res)附近,因为http的res被本地res Which is really a responseBody.json , so it has no send method. 这实际上是responseBody.json ,因此它没有send方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM