كيف يمكنني القيام برد مؤجل من معالج عمل Node.js Express؟

StackOverflow https://stackoverflow.com/questions/2159559

  •  23-09-2019
  •  | 
  •  

سؤال

استخدام يعبرnode.js) كيف أكتب رد بعد رد الاتصال؟

فيما يلي مثال أدنى. posix.cat هي وظيفة تعيد الوعد ، up أفعل شيئًا للنتيجة ، وأريد إرسال ذلك كرد.

require.paths.unshift('lib');
require('express');
var posix = require('posix');

get('/', function () {
    function up(s) {
        return s.toUpperCase();
    }
    return posix.cat('/etc/motd').addCallback(up);
});

run(3001);

العميل لا يحصل على رد.

لقد جربت أيضًا الاختلافات في هذا:

get('/2', function () {
    var myRequest = this;
    function up(s) {
        myRequest.respond(s.toUpperCase());
    }
    return posix.cat('/etc/motd').addCallback(up);
});

لكن هذا يميل إلى تحطم كل شيء:

[object Object].emitSuccess (node.js:283:15)
[object Object].<anonymous> (node.js:695:21)
[object Object].emitSuccess (node.js:283:15)
node.js:552:29
node.js:1027:1
node.js:1031:1
هل كانت مفيدة؟

المحلول

بالنسبة الى هذه, ، مشكلة النهج رقم 2 respond تم استدعاؤه قبل تعيين رمز الحالة.

هذا يعمل:

get('/2', function () {
    var myRequest = this;
    function up(s) {
        myRequest.halt(200, s.toUpperCase());
    }
    return posix.cat('/etc/motd').addCallback(up);
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top