IBM Cloud Function ไม่มีเอาต์พุต

ฉันมีปัญหาบางอย่างขณะใช้งาน IBM Cloud Function นี้:

    /**
  *
  * main() will be run when you invoke this action
  *
  * @param Cloud Functions actions accept a single parameter, which must be a JSON object.
  *
  * @return The output of this action, which must be a JSON object.
  *
  */

function main(params) {

    const https = require('https');

https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
    console.log(JSON.parse(data).explanation);
  });

}).on("error", (err) => {
  console.log("Error: " + err.message);
});

}

ปัญหาของฉันคือการเรียกใช้ฟังก์ชันนี้ครั้งแรก (อย่างน้อย 3-4 แรก) ไม่มีผลลัพธ์ การโทรครั้งต่อไปทำงานอย่างถูกต้องและบันทึกจะแสดงอย่างถูกต้อง ฉันจะแก้ไขพฤติกรรมที่คาดเดาไม่ได้นี้ได้อย่างไร แน่นอนว่าฉันต้องการดึงข้อมูลของฉันเมื่อเรียกใช้ฟังก์ชันนี้ครั้งแรก ขอบคุณ.


person Francesco_Lastrino    schedule 19.02.2019    source แหล่งที่มา
comment
ไม่แน่ใจว่าฟังก์ชันของคุณกำลังทำอะไรอยู่ แต่บ่อยครั้งที่คุณต้องคืนสัญญา นั่นเป็นสิ่งจำเป็นเพื่อให้ Cloud Functions รอให้รับข้อมูล async จากนั้นจึงสร้างผลลัพธ์ นี่คือฟังก์ชันดังกล่าว: github.com/ IBM-Cloud/github-traffic-stats/blob/master/slack/   -  person data_henrik    schedule 19.02.2019


คำตอบ (2)


Node.js ใช้โมเดลการเขียนโปรแกรมแบบอะซิงโครนัสแบบไม่บล็อก ฟังก์ชัน main นี้ส่งคืนก่อนที่การตอบสนอง HTTP จะพร้อมใช้งาน

การส่งคืนสัญญาจะทำให้คุณสามารถรอการตอบกลับ HTTP ได้

function main(params) {
  return new Promise((resolve, reject) => {
    const https = require('https');

    https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
      let data = '';

      // A chunk of data has been recieved.
      resp.on('data', (chunk) => {
        data += chunk;
      });

      // The whole response has been received. Print out the result.
      resp.on('end', () => {
        const explanation = JSON.parse(data).explanation
        console.log(explanation);

        resolve({ explanation })
      });

    }).on("error", (err) => {
      console.log("Error: " + err.message);
      reject({ error: err.message })
    });

  })
}
person James Thomas    schedule 19.02.2019

เพิ่มเติมสองสิ่งที่ต้องตรวจสอบ:

  1. ตรวจสอบให้แน่ใจว่าได้เพิ่ม .json ต่อท้ายปลายทางของคุณ
  • ตัวอย่าง: https://<ibm-domain>/api/v1/web/<username>/default/<function>.json
  1. ตรวจสอบให้แน่ใจว่าได้เลือก Enable as Web Action ในเมนูแถบด้านข้าง Endpoints

นอกจากนี้ คุณควรจะสามารถส่งคืนฟังก์ชันหลัก async แทนวัตถุ Promise ได้

async function main(params) {
  try {
    // some `await` function
  } catch (e) {
    // catch `await` errors
  }
}

module.exports = main;
person Andi    schedule 04.07.2020