gpt4 book ai didi

javascript - 悬挂回调 : return response before every callback has returned

转载 作者:行者123 更新时间:2023-11-30 16:09:50 26 4
gpt4 key购买 nike

Question: Would you consider dangling callbacks as bad node.js style or even dangerous? If so under which premise?

案例:如下所述,假设您需要调用更新某些数据的快速服务器中的数据库。然而,客户不需要被告知结果。在这种情况下,您可以立即返回响应,而不是等待异步调用完成。由于缺少更好的名称,这将被描述为悬挂回调

为什么这很有趣?因为教程和文档在大多数情况下都展示了等待的情况,在最坏的情况下教导了回调 hell 。回想一下您第一次使用 say express、mongodb 和 passport 的经历。


示例:

'use strict'
const assert = require('assert')
const express = require('express')

const app = express()

function longOperation (value, cb) {
// might fail and: return cb(err) ...here

setTimeout(() => {
// after some time invokes the callback
return cb(null, value)
}, 4000)
}

app.get('/ping', function (req, res) {
// do some declartions here
//
// do some request processesing here

// call a long op, such as a DB call here.
// however the client does not need to be
// informed about the result of the operation
longOperation(1, (err, val) => {
assert(!err)
assert(val === 1)
console.log('...fired callback here though')
return
})

console.log('sending response here...')
return res.send('Hello!')
})

let server = app.listen(3000, function () {
console.log('Starting test:')
})

最佳答案

是的,这在其他情况下基本上就是所谓的“即发即弃”服务,也可能是实现命令-查询响应分离的良好设计的第一步。

我不认为它是“悬空回调”,这种情况下的响应确认已收到请求。您最好的选择是确保您的响应包括某种超媒体,让客户稍后获得他们的请求状态,如果这是一个错误,他们可以修复新资源 URL 上的内容,告诉他们如何修复。

在用户注册工作流程的情况下考虑一下,用户必须得到管理员的批准,或者必须在获得访问权限之前确认他们的电子邮件。

关于javascript - 悬挂回调 : return response before every callback has returned,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36440525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com