![](/img/trans.png)
[英]How can I store the value of an async function to be used multiple times in a function without having to make the async call multiple times?
[英]How do I create generator function that can be used multiple times in a postman request?
我想創建一個在請求正文中使用的函數。
每次調用該函數時,它都會返回一個不同的值。 每次調用時增加1的數字。
我想在郵遞員請求中多次調用此函數,以便在整個請求正文中插入一系列數字。
例如
{
"first": {nextSequenceNumber()},
"second": {nextSequenceNumber()},
"third": {nextSequenceNumber()},
"fourth": {nextSequenceNumber()},
}
有沒有辦法做到這一點?
您可以使用內聯調用以聲明式將對象構建為javascript。
let response = {body: {
"first": {nextSequenceNumber()},
"second": {nextSequenceNumber()},
"third": {nextSequenceNumber()},
"fourth": {nextSequenceNumber()}}};
response.body.someField = ‘foo’(
在您的返回塊中(使用express.js等),發送您構建的JS對象。
您可以采用Generator
函數並采用next
調用的value屬性。
function* getNext(i) { while (true) yield i++; } var sequenceNumber = getNext(0), object = { first: sequenceNumber.next().value, second: sequenceNumber.next().value, third: sequenceNumber.next().value, fourth: sequenceNumber.next().value }; console.log(object);
同樣包裹在一個封閉
function* getNext(i) { while (true) yield i++; } var sequenceNumber = (gen => gen.next().value)(getNext(0)), object = { first: sequenceNumbert(), second: sequenceNumber(), third: sequenceNumber(), fourth: sequenceNumber() }; console.log(object);
這是一種駭人聽聞的技巧,但是它會給您一個看起來像這樣的對象:
{
"first":1,
"second":2,
"third":3,
"forth":4
}
如果將其添加到Pre-Request Script
的“ Pre-Request Script
中:
var n = 0;
function increment() { return ++n; }
function requestBody(first, second, third, forth) {
this.first = first
this.second = second
this.third = third
this.forth = forth
}
let myData = new requestBody(increment(), increment(), increment(), increment())
pm.globals.set('bodyData', JSON.stringify(myData))
您可以只使用{{bodyData}}
變量作為請求的正文:
同樣,這不是一個很好的解決方案,但可能需要反復進行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.